package com.zzx.common;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
//配置加载顺序
@Order(1)
@Component
public class DynamicDataSourceAspect {
	
	//private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSourceAspect.class);
	
	@Pointcut("@annotation(com.zzx.common.DataSource)"
            + "|| @within(com.zzx.common.DataSource)")
    public void dsPointCut()  {
    }

    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Method targetMethod = this.getTargetMethod(point);
        DataSource dataSource = targetMethod.getAnnotation(DataSource.class);//获取要切换的数据源
        if (dataSource != null)  {
        	DynamicDataSourceHolder.putDataSource(dataSource.name().name());
        }
        try {
            return point.proceed();
        }
        finally  {
        	System.out.println("**数据源:"+DynamicDataSourceHolder.getDataSouce());
            // 销毁数据源 在执行方法之后
        	//DynamicDataSourceHolder.removeDataSourceType();
        }
    }

    /**
     * 获取目标方法
     */
    private Method getTargetMethod(ProceedingJoinPoint pjp) throws NoSuchMethodException {
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method agentMethod = methodSignature.getMethod();
        return pjp.getTarget().getClass().getMethod(agentMethod.getName(), agentMethod.getParameterTypes());
    }
	
    
}
